<?php
declare (strict_types=1);

namespace app\admin\controller;

use app\BaseController;
use app\lib\exception\BaseException;
use app\middleware\admin\Auth;
use app\model\Admins;
use app\model\ClassStudent;
use app\model\ClassTime;
use app\model\Proceeds as ProceedsModel;
use app\model\School;
use app\model\Ticket;
use app\model\Ticketuse;
use app\model\TimeLog;
use think\facade\Db;
use think\Request;
use app\model\Student as StudentModel;

class Student extends BaseController
{
    protected $middleware=[Auth::class=>['except'=>'create']];
    /**
     * 显示资源列表
     * @return \think\Response
     */
    public function index($limit = 10)
    {
        $name = request()->param('name');
        $status = request()->param('status');
        $time = request()->param('time');
//        $school = request()->param('school_id');
        $id=request()->param('id');
        $data = StudentModel::with(['school','cate'])
//            ->where('school_id', $school)
            ->when($id, function ($query) use ($id) {
            $query->where('id',$id);
            })
            ->when($name, function ($query) use ($name) {
                $query->whereRaw('(concat(card_number,name,mobile) like "%' . $name . '%")');
            })
        ->when($status, function ($query) use ($status) {
                $query->where('status', $status);
            })->when($time, function ($query) use ($time) {
                $query->whereBetween('create_time', $time);
            })->paginate($limit);
        return $this->success($data);
    }


    /**
     * 学生端列表
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function one()
    {
        return $this->success(StudentModel::with('school')->find(\request()->userid));
    }

    /**
     * 延长套票时间
     * @return \think\response\Json
     */
    public function lengthenTime()
    {
        $params = \request()->param();
        $time = \app\model\InvoiceDetails::find($params['id']);
//        $create_time = strtotime($time->create_time);
        $day = intval($params['day']);

//        $new_date = date('Y-m-d H:i:s', strtotime("+$day day", $create_time));
        \app\model\InvoiceDetails::where('id',$params['id'])->inc('day',$day)->update();
        return $this->success();
    }


    /**
     * 获取学生套票
     * @param $limit
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getTicket($limit=15)
    {
        $student = request()->param('student_id');

        $data = \app\model\InvoiceDetails::
        alias('ivd')
//            ->where('ivd.state', 0)
            ->join('invoice i', 'i.id=ivd.invoice_id')
            ->where('i.student_id', $student)
            ->where('ivd.type', 4)
            ->field('ivd.*,i.number')
            ->order('ivd.id', 'desc')
            ->paginate($limit)
            ->toArray();

        foreach ($data['data'] as $key=>&$item) {

            $item['useNum'] = Ticketuse::where('invoice_details_id', $item['id'])->where('student_id',$student)->sum('num');
            $course = Ticket::where('id', $item['cid'])->find();

            $item['course'] = \app\model\Course::whereIn('id', $course['course_id'])->select()->toArray();
            $timestamp = strtotime($item['create_time']) + ($item['day'] * 24 * 60 * 60);
            $item['hereto']=  date('Y-m-d H:i:s', $timestamp);
            array_walk($item['course'], function (&$query) {
//                $query['teacher'] = implode(',', Admins::whereIn('id', $query['admins_id'])->find('ename'));
                $query['teacher'] = Admins::whereIn('id', $query['admins_id'])->value('ename');
            });
            unset($item['ticket']);

        }

        return $this->success($data);
    }


    /** 学生已报名课程
     * @param $limit
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getSign($limit=15)
    {
        $student = request()->param('student_id');

        // $data = \app\model\InvoiceDetails::
        //     alias('ivd')
        //   ->where('ivd.state', 0)
        //     ->join('invoice i', 'i.id=ivd.invoice_id')
        //     ->leftJoin('class_student cs','cs.invoice_details_id=ivd.id')
        //     ->leftJoin('classtime ct','ct.id=cs.classtime_id')
        //     ->where('i.student_id',$student)
        //     ->whereIn('ivd.type', [3,4])
        //     ->field('ivd.*,i.number,i.student_id,ct.start_time,ct.end_time,cs.id classStudentid,ct.admin_id')
        //     ->order('ivd.id', 'desc')
        //     ->paginate($limit)
        //     ->toArray();


        $data=ClassTime::where('cs.student_id',$student)->alias('ct')
            ->leftJoin('class_student cs','ct.id=cs.classtime_id')
            ->leftJoin('invoice_details ivd', 'cs.invoice_details_id=ivd.id')
            ->leftJoin('invoice inv', 'inv.id=ivd.invoice_id')
            ->leftJoin('course c','ct.course_id=c.id')
            ->field('ivd.*,ct.start_time,ct.end_time,ct.date,ct.time1,cs.id classStudentid,ct.admin_id,cs.classtime_id,ct.course_id,cs.state as statuste,inv.number as invnumber')
            ->where('cs.state','<>','取消')
            ->paginate($limit)
            ->toArray();
        // dd($data);
        $count=Db::query("SELECT classtime_id,count(*) as count FROM class_student  group by classtime_id having count>0 ");

        $count=array_column($count,'count','classtime_id');
        foreach ($data['data'] as $key=>&$item) {
            if($item['type']==3){
                $item['useNum'] = 0;

                $course = \app\model\Course::where('id', $item['cid'])->find();
                $item['course'] = \app\model\Course::where('id', $item['cid'])->find();

                // $item['count']=ClassTime::where('admin_id',$item['admin_id'])
                //         ->where('classroom_id',$item['course']['classroom_id'])
                //         ->group('admin_id','start_time','classroom_id')
                //         ->count().'/'. $course['num'];

                $item['count']= $count[$item['classtime_id']].'/'. $course['num'];
//                $timestamp = strtotime($item['create_time']) + ($course['deadline'] * 24 * 60 * 60);
                $item['hereto']= 0;
                $item['course']['teacher'] = Admins::where('id',$item['admin_id'])->value('ename');

                $item['teacher']=Admins::where('id',$item['admin_id'])->value('ename');
                unset($item['ticket']);
            }else{
                $item['useNum'] = Ticketuse::where('invoice_details_id', $item['id'])->where('student_id',$student)->sum('num');
                $course = Ticket::where('id', $item['cid'])->find();
                $item['course'] = \app\model\Course::where('id', $item['course_id'])->find();

//                $count=Db::query("SELECT classtime_id,count(*) as count FROM class_student  group by classtime_id having count>0 ");

//                $count=array_column($count,'count','classtime_id');


                $item['count']= $count[$item['classtime_id']].'/'. $item['course']['num'];
                if(empty($item['create_time'])){
                    $timestamp = strtotime(date('Y-m-d H:i')) + ($course['deadline'] * 24 * 60 * 60);
                }else{
                    $timestamp = strtotime($item['create_time']) + ($course['deadline'] * 24 * 60 * 60);
                }
//                $timestamp = strtotime($item['create_time']) + ($course['deadline'] * 24 * 60 * 60);
                $item['hereto']=  date('Y-m-d H:i:s', $timestamp);
                $item['course']['teacher'] = Admins::where('id',$item['admin_id'])->value('ename');
                // foreach ($item['course'] as &$v){
                //     $v['teacher']=Admins::where('id',$v['admins_id'])->value('name');
                //     dd($v);
                // }

                // array_walk($item['course'], function (&$query) {
                //     dd($query);
                //     $query['teacher'] = Admins::where('id',$query['admins_id'])->value('name');
                // });
                $item['teacher']=Admins::where('id',$item['admin_id'])->value('ename');
                unset($item['ticket']);
            }


        }

        return $this->success($data);
    }

    /**
     * 保存新建的资源
     *
     * @param \think\Request $request
     * @return \think\Response
     */
    public function create(Request $request)
    {

        $params = $request->param();
        $params['number'] = getNumber('學生');
        $student= StudentModel::where('username',$params['username'])->find();
        if(empty($student)){
            StudentModel::create($params);
        }else{
            throw new BaseException(['msg'=>'該登錄賬號已被註冊']);
        }
        return $this->success();
    }


    /**
     * 保存更新的资源
     *
     * @param \think\Request $request
     * @param int $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        $params=$request->param();
        if(empty($params['password'])){
            unset($params['password']);
        }
        StudentModel::where('id', $id)->update($params);
        return $this->success();
    }

    /**
     * 删除指定资源
     *
     * @param int $id
     * @return \think\Response
     */
    public function delete($id)
    {
        StudentModel::where('id', 'in', $id)->delete();
        return $this->success();
    }

    /**
     * 欠款
     */
    public function arrearage($limit=15)
    {
        $student=\request()->param('student_id');
        $pay=request()->param('pay',1);
//        $data= \app\model\Invoice::where('student_id',$student)->where('pay',$pay)->paginate($limit);
        $data=Db::name('invoice_details')->alias('ivd')
                 ->leftJoin('invoice i','i.id=ivd.invoice_id')
                 ->leftJoin('school s','s.id=i.school_id')
                 ->leftJoin('proceeds_details ps','ps.invoice_details_id=ivd.id')
                 ->where('i.student_id',$student)
                 ->where('i.pay',$pay)
                 ->field('ivd.*,i.number,i.price as invoice_money,s.name as school_name,ps.debt,ps.grandtotal,ps.money')
                 ->paginate($limit);
        return $this->success($data);
    }

    /**
     * 消費
     */
    public function consume($limit=15)
    {

        $type = request()->param('type');
        $time = request()->param('time');
//        $school = request()->param('school_id');
        $student_id = request()->param('student_id');

        $data = ProceedsModel::with(['paytype','school','admin'])
//            ->where('school_id', $school)
            ->where('student_id',$student_id)
            ->when($time, function ($query) use ($time) {
            $query->whereBetween('create_time', $time);
        })->order('id', 'desc')->paginate($limit)->toArray();
        $list['data']=$data;

        $money=ProceedsModel::where('student_id',$student_id)
            ->when($time, function ($query) use ($time) {
                $query->whereBetween('create_time', $time);
            })->sum('money');
        $refund=ProceedsModel::where('student_id',$student_id)
            ->when($time, function ($query) use ($time) {
                $query->whereBetween('create_time', $time);
            })->sum('refund');
        $debt=ProceedsModel::where('student_id',$student_id)
            ->when($time, function ($query) use ($time) {
                $query->whereBetween('create_time', $time);
            })->sum('debt');
        $list['money']=$money;
        $list['refund']=$refund;
        $list['debt']=$debt;

        return $this->success($list);
    }

    /**
     * 导入
     */
    public function conduct()
    {
        $data = json_decode(request()->param('data'),true);

        foreach ($data as $key => &$value) {
             $value['number']=getNumber('學生');
            if (!empty($value['identity'])) {
                $identity = StudentModel::where('identity', $value['identity'])->find();
                if ($identity) throw new BaseException(['msg' => '第' . ($key + 1) . '行身份證重複請修改後上傳']);
            }
        }
        $model = new StudentModel();
        $model->saveAll($data);
        return $this->success();
    }


    public function edit()
    {
        $params = request()->param();
        $AdminName=Admins::where('id',\request()->userid)->value('name');
//        Db::startTrans();

        foreach ($params['student'] as $item) {

            $name=\app\model\Student::where('id',$item['student_id'])->value('name');

                $class = ClassTime::alias('ct')
                    ->join('class_student cs', 'cs.classtime_id=ct.id')
                    ->join('classroom cr', 'cr.id=ct.classroom_id', 'left')
                    ->join('invoice_details ind', 'ind.id=cs.invoice_details_id', 'left')
                    ->join('invoice i', 'i.id=ind.invoice_id', 'left')
                    ->where('i.status', 1)
                    ->where('ind.status', 1)
//                    ->where('ct.admin_id', $item['admin_id'])
//                    ->where('ct.classroom_id', $item['classroom_id'])
                    ->where('ct.course_id', $item['course_id'])
                    ->where('ct.start_time', $item['start_time'])
                    ->where('ct.end_time', $item['end_time'])
                    ->where('cs.type', 1)
                    ->where('cs.state', '<>', '取消')
                    ->field('ct.*')
                    ->find();

                if ($class) {
                    $tab = ClassStudent::where('classtime_id', $class['id'])->where('student_id', $item['student_id'])->where('type', 1)->find();
                    if ($tab) { //需要判断是否已加入
                        Db::rollback();
                        throw new \Exception("該學生已經加入該時間段的課程，請勿重複操作");
                    }
//                    $course=\app\model\Course::where('id',$item['end_time'])->find();
                    $num= StudentModel::where('id',$item['student_id'])->value('num');
                    if($num<=0){
                        throw new \Exception("該學生的調課次數已超出限制，請勿重複操作");
                    }
                    ClassStudent::where('id', $item['classStudentid'])->update(['classtime_id' => $class['id']]);
                    $teacher=Admins::where('id',$item['admin_id'])->value('name');
                    $room=\app\model\Classroom::where('id',$item['classroom_id'])->value('name');
                    TimeLog::create([
                        'school_id'=>$params['school_id'],
                        'classtime_id'=>$class['id'],
                        'content'=>'在' . date('Y-m-d h:i:s', time()) . '時，' . $AdminName . '管理員修改了學生:' . $name . '的課時狀態為調堂，並修改課時時間為：' . $item['start_time'] . '-' . $item['end_time'] . '課時的教師為：' . $teacher . ',教室为：' . $room
                    ]);
                    StudentModel::where('id',$item['student_id'])->dec('num')->update();
                } else {
                   $num= StudentModel::where('id',$item['student_id'])->value('num');
                   if($num<=0){
                       throw new \Exception("該學生的調課次數已超出限制，請勿重複操作");
                   }
                    $classtime = ClassTime::create([
                        'admin_id' => $item['admin_id'],
                        'classroom_id' => $item['classroom_id'],
                        'course_id' => $item['course_id'],
                        'time1' => '',
                        'date' => "",
                        'start_time' => $item['start_time'],
                        'end_time' => $item['end_time'],
                        'state' => '調堂'
                    ]);
                    ClassStudent::where('id', $item['classStudentid'])->update(['classtime_id' => $classtime->id]);
                    $teacher=Admins::where('id',$item['admin_id'])->value('name');
                    $room=\app\model\Classroom::where('id',$item['classroom_id'])->value('name');
                    TimeLog::create([
                        'school_id'=>$params['school_id'],
                        'classtime_id'=>$classtime->id,
                        'content'=>'在' . date('Y-m-d h:i:s', time()) . '時，' . $AdminName . '管理員修改了學生:' . $name . '的課時狀態為調堂，並修改課時時間為：' . $item['start_time'] . '-' . $item['end_time'] . '課時的教師為：' . $teacher . ',教室为：' . $room
                    ]);

                    StudentModel::where('id',$item['student_id'])->dec('num')->update();
                }

//        }
            return $this->success();
//        try {
//            ClassTime::where('id',$id)->update(['remark'=>$params['remark'] ?? '']);
//
//
//            Db::commit();
//            return $this->success();
//        }catch (\Exception $e){
//            Db::rollback();
//        }

        }
    }


    public function derive($limit=15)
    {
        $school_id=\request()->param('school_id');
        $school=\request()->param('school');
        $status=\request()->param('status');
        $type=\request()->param('type');
        $sex=\request()->param('sex');
        $education=\request()->param('education');
        $time=\request()->param('time');

       $data= StudentModel::with(['cate','school'])
       ->when($school,function ($query) use($school){
                    $query->where('school_id',$school);
        })->when($status,function ($query) use($status){
                $query->where('status',$status);
        })->when($type,function ($query) use($type){
            $query->where('student_type_id',$type);
        })->when($sex,function ($query) use($sex){
            $query->where('sex',$sex);
        })->when($education,function ($query) use($education){
                $query->where('education',$education);
        })->when($time,function ($query) use($time){
               $query->whereBetween('create_time', $time);
        })->when($school_id,function ($query) use($school_id){
           $admin = Admins::where('id', request()->userid)->find();
           $s= School::where('id', 'in', $admin->school_id)->select()->toArray();
           $query->where('school_id','in',array_column($s,'id'));
       })->paginate($limit);

       return $this->success($data);
    }


}
